import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import { useMount, useMouse } from 'ahooks'
import zhCN from 'antd/locale/zh_CN'
import { useRequest } from 'alova/client'
import { ConfigProvider, App, notification } from 'antd'
import { lazy, Suspense, useEffect, useState } from 'react'
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
import { Http } from '../Utils/Api'
import { IndexedDBFun } from '../Utils/IndexedDB'
import { judgeBrowserVersion, debuggerFun } from '../Utils'

import { drawerStore, pageStore } from '../Config/zustand'

dayjs.locale('zh-cn')

const { port } = window.location

const Loading = lazy(() => import('../Page/Loading/LoadSvg'))

const Login = lazy(() => import('../Login'))
const Admin = lazy(() => import('../Admin'))
const Start = lazy(() => import('../Start'))

const RouterMapping = [
    { path: '/', element: <Login /> },
    { path: 'Admin', element: <Admin /> },
    { path: 'Start/:page?/:id?', element: <Start /> },
]

const router = createBrowserRouter(RouterMapping)

const NavList = [
    { value: 'A01', label: '项目选择' },
    { value: 'A02', label: '业务流程' },
    { value: 'A03', label: '项目主题' },
    { value: 'A04', label: 'DEV样式' },
    { value: 'A05', label: '全局样式' },
]

const COLORLIST = ['#f5222d', '#fa541c', '#fa8c16', '#faad14', '#d4b106', '#a0d911', '#52c41a', '#13c2c2', '#1677ff', '#2f54eb', '#722ed1', '#eb2f96']


const RouterInit = () => {
    window.webDB = IndexedDBFun()
    // if (!port) debuggerFun()
    const { pageActive, pageList, updateActive, updateList } = pageStore()

    const { clientX, clientY } = useMouse()
    const [api, contextHolder] = notification.useNotification();
    const { send } = useRequest(data => Http(data), { immediate: false })

    const [Right, setRight] = useState(0)
    const [Show, setShow] = useState(false)
    const [Project, setProject] = useState([])

    useEffect(() => {
        if (port && !Show) {
            if (clientX < 80 && clientX > 0) setRight(120)
            else setRight(0)
        }
    }, [clientX, clientY])

    useMount(() => {
        send({ method: 'get', url: 'getProject', params: { uuid: 'PorjectList' } }).then(res => {
            const { Project } = res
            setProject(Project)
        }).catch(err => {
            console.log(err)
        })
    })

    const onNavClick = async (value) => {
        const { pathname } = window.location
        const checkAdminPath = () => {
            if (pathname !== '/Admin') {
                api.error({ key: 'ADMIN_OPTIONS', message: '无法配置', description: '登录后台,才能配置项目!', placement: 'topLeft' })
                return false
            }
            return true
        }
        const addItemIfNotExists = (uuid, label, url) => {
            const itemStatus = pageList.find(v => v.key === uuid);
            if (!itemStatus) updateList([...pageList, { key: uuid, label, url, icon: 'shou', type: 'diy' }])
            updateActive(uuid)
        }
        const actionMap = {
            'A01': () => { setShow(true); setRight(0) },
            'A02': () => { if (checkAdminPath()) addItemIfNotExists('00000000-0000-0000-0000-000000000101', '业务流程', 'SetOperationFlow') },
            'A03': () => { if (checkAdminPath()) addItemIfNotExists('00000000-0000-0000-0000-000000000102', '项目主题', 'SetProjectTheme') },
            'A04': () => { if (checkAdminPath()) addItemIfNotExists('00000000-0000-0000-0000-000000000103', '后台路由', 'SetDEVTheme') },
            'A05': () => { if (checkAdminPath()) addItemIfNotExists('00000000-0000-0000-0000-000000000104', '全局样式', 'SetGlobalStyle') }
        }
        const action = actionMap[value]
        if (action) action()
    }

    return (
        <ConfigProvider locale={zhCN}>
            {contextHolder}
            <App>
                <Suspense fallback={<Loading />}>
                    {judgeBrowserVersion() ? <RouterProvider router={router} /> : <VersionTips />}
                </Suspense>
            </App>

            {port &&
                <div className='ADMIN_OPTION' style={{ transform: `translateX(${Show ? 0 : -100}%)` }} >
                    <div className='ADMIN_OPTION_NAV'>
                        {NavList.map(({ value, label }) =>
                            <div
                                key={value}
                                className='ADMIN_OPTION_NAVITEM'
                                style={{ transform: `translateX(${Right}px)` }}
                                onClick={() => onNavClick(value)}
                            >
                                <div>{label}</div>
                            </div>
                        )}
                        <div className='ADMIN_OPTION_NAV_CLOSE' onClick={() => setShow(false)}>CLOSE</div>
                    </div>

                    <div className='ADMIN_OPTION_LIST'>
                        {Project.map(({ url, label, title }, index) =>
                            <div
                                key={url}
                                style={{ background: COLORLIST[index % 12] }}
                                onClick={() => (window.location.href = `http://${url}:${window.location.port}`)}
                            >
                                <div>{label}</div>
                                <div>{title}</div>
                            </div>
                        )}
                    </div>

                    <svg>
                        <filter id="goo">
                            <feGaussianBlur in="SourceGraphic" stdDeviation="10" result="blur" />
                            <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 20 -10" result="goo" />
                            <feComposite in="SourceGraphic" in2="goo" operator="atop" />
                        </filter>
                    </svg>
                </div>
            }
        </ConfigProvider>
    )
}

export default RouterInit